from dao.DAOQuanLyNhanVien import DaoQuanLyNhanVien
from datetime import datetime
from google.appengine.ext import db
import json as simplejson
from models.LoaiNhanVien import LoaiNhanVien
from models.NhanVien import NhanVien
import WSGI
import logging
import math
import webapp2
from google.appengine.api import users
from utils.permission_required import permission_required

logger = logging.getLogger("GUIQuanLyNhanVien")

class GuiQuanLyCongNo(webapp2.RequestHandler):
    
    perm = 'KeToan.QuanLyCongNo'
    priv = ''
    @permission_required
    def get(self):
                
        nv = DaoQuanLyNhanVien.getNhanVienByUsername(users.get_current_user().nickname())
        lstPerm = DaoQuanLyNhanVien.getListStaffPriviledge(nv.key().id())
        lstMenu = []
        lstNewPerm = []
        for perm in lstPerm:
            lstMenu.append(perm[:perm.index('.')])
            lstNewPerm.append(perm.replace('.', '-'))
        lstMenu = list(set(lstMenu))
        
        lstKhachHang, _ = DaoQuanLyNhanVien.getListKhachHang('', 1000, 0, '');
        for item in lstKhachHang:
            item['tenKhachHang'] = str(item['id']) + ' - ' + item['tenKhachHang']
        
        template_values = {
                        'lstPerm': lstNewPerm,
                        'lstMenu': lstMenu,
                        'nickname': users.get_current_user().nickname(),
                        'signOutUrl': users.create_logout_url(self.request.uri),
                        'lstKhachHang': lstKhachHang
        }

        template = WSGI.jinja_environment.get_template('/html/QuanLyCongNo.html')
        self.response.out.write(template.render(template_values))


class JsonRequestHandler(webapp2.RequestHandler):
    perm = 'KeToan.QuanLyCongNo'
    priv = ''
    @permission_required
    def get(self):
        funcName = self.request.get('func')
        funcMapping = {'getListCongNo': 'getListCongNo'}
        func = getattr(self, funcMapping[funcName]);
        result = func();
        self.response.out.write(result)
    
    def post(self):
        return self.get()
    
    def getListCongNo(self):
        gridRowNum = int(self.request.get('rows'))
        pageNum = int(self.request.get('page'))
        maKH = self.request.get('maKH')
        sortBy = self.request.get('sord')
        
        rows, rowNum = DaoQuanLyNhanVien.getListCongNo(maKH, gridRowNum, int((pageNum-1)*gridRowNum), sortBy)
        for item in rows:
            item['tenKH'] = str(item['id']) + ' - ' + item['tenKhachHang']
        
        results = {'page': pageNum, 'total': math.ceil(float(rowNum)/gridRowNum), 'records':rowNum, 'rows':rows}
        return simplejson.dumps(results)
        
        
            
        